package cn.lopr.hfbdqn.service;

import cn.lopr.hfbdqn.annotaion.Auth;
import cn.lopr.hfbdqn.common.Result;
import cn.lopr.hfbdqn.configuration.AuthInfo;
import cn.lopr.hfbdqn.dao.UserMapper;
import cn.lopr.hfbdqn.pojo.User;
import cn.lopr.hfbdqn.route.UserRoute;
import cn.lopr.hfbdqn.util.jwt.JwtUtil;
import cn.lopr.mvc.frame.annotaion.Autowired;
import cn.lopr.mvc.frame.annotaion.Service;
import cn.lopr.util.ObjectUtils;
import cn.lopr.util.StringUtils;

import java.util.HashMap;

/**
 * @author shuangyang7
 * @date 2021/7/19 11:03
 */
@Service
public class UserService implements UserRoute {

    @Autowired
    UserMapper userMapper;

    @Autowired
    JwtUtil jwtUtil;

    public Result<?> getAll() {

        //List<User> users = SQLSessionFactory.getMapper(UserMapper.class).selectAll();

        return new Result<>(Result.SUCCESS, userMapper.selectAll());
    }

    public User getUserById(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    public Result<?> updById(String id) {
        return null;
    }

    public Result<?> delById(String id) {
        return null;
    }

    @Override
    public Result<?> login(String username, String password) {
        if (StringUtils.isEmpty(username)) {
            return new Result<>(Result.ERROR, "请输入用户名");
        }
        if (StringUtils.isEmpty(password)) {
            return new Result<>(Result.ERROR, "请输入密码");
        }

        final User user = userMapper.getByUsernameAndPassword(username, password);
        if (ObjectUtils.isEmpty(user)) {
            return new Result<>(Result.ERROR, "登录失败请检查用户信息");
        }
        user.setUserPassword(null);

        return new Result<>(Result.SUCCESS, "登录成功", new HashMap<String, Object>() {{
            put("token", jwtUtil.createJWT(user.getUserId() + "", user.getUserName(), "user"));
            put("info", user);
        }});
    }

    @Auth
    @Override
    public Result<?> getUserInfo() {
        User user = AuthInfo.get();
        user.setUserPassword(null);
        return new Result<>(Result.SUCCESS, user);
    }

    @Override
    public Result<?> logout() {

        return null;
    }

    @Override
    public Result<?> requestBodyTest(User user) {
        System.out.println("run ... ");
        return new Result<>(Result.SUCCESS, user);
    }


}
